<template>
  <a-modal :width="1000" v-model:visible="showEditDialog" :title="currentItem.id ? '编辑报价' : '新增报价'" top="8vh" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <a-steps type="arrow" :small="true" :current="currentStep" @change="setCurrent" changeable style="margin-bottom: 20px">
      <a-step>填写报价信息</a-step>
      <a-step>关联报价产品</a-step>
    </a-steps>
    <div class="add-con">
      <a-form v-show="currentStep == 1" ref="formRef" :model="formInfo" :rules="rules">
        <a-row>
          <a-col :span="6">
            <a-form-item field="supplier.id" label="供应商：" label-col-flex="80px">
              <p v-if="currentItem.id">{{ currentItem.supplierName }}-{{ currentItem.supplierCode }}</p>
              <a-select v-else v-model="formInfo.supplier" value-key="id" placeholder="" allow-search>
                <a-option v-for="(item, i) in supplierList" :key="i" :value="item" :label="item.supplierName" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="user.id" label="采购员：" label-col-flex="100px">
              <a-select v-model="formInfo.user" value-key="id" placeholder="" allow-search>
                <a-option v-for="(item, i) in userList" :key="i" :value="item" :label="item.userName" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="deliveryDays" label="交期：" label-col-flex="100px">
              <a-input-number v-model="formInfo.deliveryDays" :precision="0" placeholder="" :min="0" />
              <span style="margin-left: 5px">天</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="moq" label="最小起订量：" label-col-flex="100px">
              <a-input-number v-model="formInfo.moq" :precision="0" placeholder="" :min="0" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-item field="currency" label="币种：" label-col-flex="80px">
              <a-select v-model="formInfo.currency" placeholder="" allow-search>
                <a-option :value="item" :label="item" v-for="(item, i) in Object.keys(currencySymbol)" :key="i" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="invoiceType" label="发票类型：" label-col-flex="100px">
              <a-select v-model="formInfo.invoiceType" placeholder="">
                <a-option :value="1" label="普票" />
                <a-option :value="2" label="专票" />
                <a-option :value="0" label="不开票" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="parTaxRate" label="票面税率：" label-col-flex="100px">
              <a-input-number v-model="formInfo.parTaxRate" :precision="0" placeholder="" :min="0" @change="changeParTaxRate" />
              <span style="margin-left: 5px">%</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="refundTaxRate" label="退税率：" label-col-flex="100px">
              <a-input-number v-model="formInfo.refundTaxRate" :precision="0" placeholder="" :min="0" />
              <span style="margin-left: 5px">%</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item hide-label>
              <a-radio-group v-model="formInfo.quoteType">
                <a-radio :value="1">非梯度报价</a-radio>
                <a-radio :value="2">梯度报价</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="formInfo.quoteType === 1">
          <a-col :span="7">
            <a-form-item field="priceInfo.price" label="不含税单价：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <a-input-number v-model="formInfo.priceInfo.price" @change="changePrice(formInfo.priceInfo, 'price')" :precision="2" placeholder="" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="税额：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <span>{{ ((Number(formInfo.priceInfo.price || 0) * Number(formInfo.parTaxRate || 0)) / 100).toFixed(2) }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item field="priceInfo.taxPrice" label="含税单价：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <a-input-number v-model="formInfo.priceInfo.taxPrice" :precision="2" placeholder="" @change="changePrice(formInfo.priceInfo, 'taxPrice')" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="可退税额：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <span>{{ ((Number(formInfo.priceInfo.price || 0) * Number(formInfo.refundTaxRate || 0)) / 100).toFixed(2) }}</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-else>
          <a-col :span="24">
            <a-table class="table-singe-line" ref="tableRef" row-key="id" :data="formInfo.quoteItems" size="mini" :bordered="false" :pagination="false">
              <template #columns>
                <a-table-column :width="120">
                  <template #title>
                    <p>
                      <span class="warningColor">*</span>
                      <span>数量</span>
                    </p>
                  </template>
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="rowIndex + 'quantity'" hide-label style="margin-bottom: 0">
                      <span style="margin-right: 5px">>=</span>
                      <a-input-number v-model="record.quantity" style="width: 100px" :precision="0" placeholder="请输入" :min="0" />
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column :width="120">
                  <template #title>
                    <p>
                      <span class="warningColor">*</span>
                      <span>不含税单价</span>
                    </p>
                  </template>
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="rowIndex + 'price'" hide-label style="margin-bottom: 0">
                      <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                      <a-input-number v-model="record.price" style="width: 100px" @change="changePrice(record, 'price')" :precision="2" placeholder="请输入" :min="0" />
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="税额" :width="100">
                  <template #cell="{ record }">
                    <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                    <span>{{ ((Number(record.price || 0) * Number(formInfo.parTaxRate || 0)) / 100).toFixed(2) }}</span>
                  </template>
                </a-table-column>
                <a-table-column :width="120">
                  <template #title>
                    <p>
                      <span class="warningColor">*</span>
                      <span>含税单价</span>
                    </p>
                  </template>
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="rowIndex + 'taxPrice'" hide-label style="margin-bottom: 0">
                      <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                      <a-input-number v-model="record.taxPrice" style="width: 100px" @change="changePrice(record, 'taxPrice')" :precision="2" placeholder="请输入" :min="0" />
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="可退税额" :width="100">
                  <template #cell="{ record }">
                    <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                    <span>{{ ((Number(record.price || 0) * Number(formInfo.refundTaxRate || 0)) / 100).toFixed(2) }}</span>
                  </template>
                </a-table-column>
                <a-table-column title="操作" :width="100">
                  <template #cell="{ rowIndex }">
                    <a-space>
                      <a-button type="text" @click="formInfo.quoteItems.splice(rowIndex + 1, 0, {})">添加</a-button>
                      <a-button type="text" v-if="formInfo.quoteItems.length > 1" @click="formInfo.quoteItems.splice(rowIndex, 1)">移除</a-button>
                    </a-space>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-form>
      <div class="product-w" v-show="currentStep == 2">
        <div style="margin-bottom: 10px" class="flex-c">
          <a-space style="margin-right: 40px">
            <FilterKeyword ref="filterKeywordRef" :currentItem="filterVal" @search="searchPro" />
            <a-button type="primary" @click="filterKeywordRef.search()">搜索</a-button>
          </a-space>
          <a-space>
            <a-button class="gray-outline" @click="openChooseProductDialog">添加报价产品</a-button>
            <a-button class="gray-outline" @click="batchDelete">移除</a-button>
          </a-space>
        </div>
        <a-table class="table-two-line" ref="tableRef" row-key="sku" :data="filterProductItems" @selection-change="selectColumn" :row-selection="rowSelection" :scroll="{ y: 'calc(84vh - 260px)' }" size="mini" :bordered="false" :pagination="false">
          <template #columns>
            <a-table-column data-index="sort" title="序号" :width="45">
              <template #cell="{ rowIndex }">
                <p>{{ rowIndex + 1 }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="img" title="图片" :width="60">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column title="产品名称/类目" :width="180">
              <template #cell="{ record }">
                <TextLimit :rows="1">{{ record.productName }}</TextLimit>
                <p>{{ record.cateName || '--' }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="sku" title="经销商SKU" :width="120">
              <template #cell="{ record }">
                <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
              </template>
            </a-table-column>
            <a-table-column data-index="spu" title="经销商SPU" :width="120" />
            <a-table-column data-index="ssku" title="供应商SKU" :width="120" />
            <a-table-column data-index="sspu" title="供应商SPU" :width="120" />
            <a-table-column title="操作" :width="60">
              <template #cell="{ record }">
                <a-popconfirm content="确定是否移除?" @ok="singleRemove(record)" type="error">
                  <a-button type="text">移除</a-button>
                </a-popconfirm>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button class="gray-outline" @click="closedDialog()">取消</a-button>
        <a-button :disabled="submitLoading" type="primary" @click="submitData(10)">保存并提交审核</a-button>
        <a-button :disabled="submitLoading" type="primary" @click="submitData(1)">保存</a-button>
      </a-space>
    </template>
  </a-modal>
  <!-- 选择采购产品 -->
  <ChooseQuotationProduct v-if="showChooseProductDialog" :categoryList="categoryOptions" :supplierId="$extract(formInfo.supplier, 'id')" :isShow="showChooseProductDialog" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import { createPurchaseQuote, updatePurchaseQuote } from '@/api/purchase'
  import { getCategoryList } from '@/api/product'
  import ChooseQuotationProduct from './chooseQuotationProduct.vue'
  import { currencySymbol } from '@/utils/globalData'
  import { Message, Modal } from '@arco-design/web-vue'
  import FilterKeyword from '@/components/Form/filterKeyword.vue'
  onMounted(() => {
    getCategory()
    if (props.currentItem.id) {
      setDefaultData()
    }
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    userList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    supplierList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })
  const rules = ref({
    'supplier.id': [{ required: true, message: '请选择供应商' }],
    'user.id': [{ required: true, message: '请选择采购员' }],
    deliveryDays: [{ required: true, message: '请输入交期' }],
    moq: [{ required: true, message: '请输入最小起订量' }],
    currency: [{ required: true, message: '请选择货币' }],
    invoiceType: [{ required: true, message: '请选择发票类型' }],
    parTaxRate: [{ required: true, message: '请输入票面税率' }],
    refundTaxRate: [{ required: true, message: '请输入退税率' }],
    'priceInfo.price': [{ required: true, message: '请输入不含税单价' }],
    'priceInfo.taxPrice': [{ required: true, message: '请输入含税单价' }],
  })
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const currentStep = ref(1)
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({
    priceInfo: {},
    quoteItems: [{}],
    quoteType: 1,
  })
  const filterVal: any = {
    key: 'sku',
    keyItems: [
      { label: '经销商SKU', value: 'sku' },
      { label: '经销商SPU', value: 'spu' },
      { label: '供应商SKU', value: 'ssku' },
      { label: '产品名称', value: 'productName' },
    ],
    keyWidth: '120',
    value: null,
    placeholder: '请输入',
    label: '',
    width: 200,
    isMultiple: true,
  }
  const productItems = ref<Array<any>>([])
  const filterProductItems = ref<Array<any>>([])
  const categoryOptions = ref<Array<any>>([])
  const submitLoading = ref(false)
  const showChooseProductDialog = ref(false)
  const formRef = ref()
  const selectIds = ref([])
  const filterKeywordRef = ref()

  // 选中
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 获取类目列表
  async function getCategory() {
    const res: any = await getCategoryList()
    categoryOptions.value = res?.data || []
  }
  // 修改单价关联
  function changePrice(item: any, key: string) {
    console.log(item)
    let parTaxRate = formInfo.value.parTaxRate || 0
    // 修改不含税单价
    if (key === 'price') {
      let val = Number(((item.price || 0) * (1 + parTaxRate / 100)).toFixed(2))
      item.taxPrice = val
    }
    // 修改含税单价
    if (key === 'taxPrice') {
      let val = Number(((item.taxPrice || 0) / (1 + parTaxRate / 100)).toFixed(2))
      item.price = val
    }
  }
  function changeParTaxRate() {
    changePrice(formInfo.value.priceInfo, 'price')
    formInfo.value.quoteItems.forEach((el: any) => {
      changePrice(el, 'price')
    })
  }
  // 添加初始化数据
  function setDefaultData() {
    formInfo.value = JSON.parse(JSON.stringify(props.currentItem))
    if (formInfo.value.supplierId) {
      formInfo.value.supplier = {
        id: formInfo.value.supplierId,
        supplierName: formInfo.value.supplierName,
        supplierCode: formInfo.value.supplierCode,
      }
    }
    if (formInfo.value.purchaseUid) {
      formInfo.value.user = {
        id: formInfo.value.purchaseUid,
        userName: formInfo.value.purchaseUname,
      }
    }
    productItems.value = formInfo.value.quoteProducts
    filterItem()
    // 非梯度报价
    if (formInfo.value.quoteType === 1) {
      formInfo.value.priceInfo = formInfo.value.quoteItems?.[0] || {}
    } else {
      formInfo.value.priceInfo = {}
    }
  }
  function filterItem() {
    let valArr = filterVal.value?.split(',') || []
    valArr = valArr.filter((str: string) => str?.trim())
    let key = filterVal.key
    if (!key || !valArr.length) {
      filterProductItems.value = JSON.parse(JSON.stringify(productItems.value))
    } else {
      filterProductItems.value = []
      productItems.value.forEach((el: any) => {
        if (valArr.includes(el[key])) {
          filterProductItems.value.push(el)
        }
      })
    }
  }
  // 筛选产品列表
  function searchPro(info?: any) {
    filterVal.key = info?.key
    filterVal.value = info?.value
    filterItem()
  }
  function setItemInfoByProduct(item: any) {
    let obj = {
      productId: item.id,
      productImg: item.productPicList?.[0]?.url,
      productName: item.skuName,
      sku: item.sku,
      spu: item.spu,
      cateId: item.category?.id,
      cateName: item.category?.name,
    }
    return obj
  }
  // 添加产品
  function chooseProduct(list: Array<any>) {
    list.forEach((el: any) => {
      if (!productItems.value.find((item: any) => el.sku === item.sku)) {
        productItems.value.push(setItemInfoByProduct(el))
      }
    })
    filterItem()
  }
  // 打开选择报价产品
  function openChooseProductDialog() {
    if (!formInfo.value.supplier?.id) {
      Message.error('请先选择供应商')
      currentStep.value = 1
      return
    }
    showChooseProductDialog.value = true
  }
  // 单个移除
  function singleRemove(row: any) {
    let index = productItems.value.findIndex((el: any) => el.sku === row.sku)
    if (index > -1) {
      productItems.value.splice(index, 1)
    }
    filterItem()
  }
  // 批量移除
  function batchDelete() {
    if (!selectIds.value.length) {
      return Message.error('请选择产品')
    }
    Modal.confirm({
      title: '提示',
      content: `请再次确认，移除选中的产品`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: () => {
        selectIds.value.forEach((sku: string) => {
          let index = productItems.value.findIndex((el: any) => el.sku === sku)
          if (index > -1) {
            productItems.value.splice(index, 1)
          }
        })
        filterItem()
      },
    })
  }
  // 关闭
  function closedDialog() {
    emit('closed')
    showEditDialog.value = false
  }
  function setCurrent(current: number) {
    currentStep.value = current
  }
  // 校验
  async function validInfo() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) {
      currentStep.value = 1
      return false
    }
    // 梯度报价的校验
    if (formInfo.value.quoteType === 2) {
      let rules = {}
      formInfo.value.quoteItems.forEach((el: any, i: number) => {
        let arr = ['quantity', 'price', 'taxPrice']
        arr.forEach((key: string) => {
          if (isNull(el[key])) {
            rules[i + key] = {
              status: 'error',
              message: '必填',
            }
          }
        })
      })
      formRef.value.setFields(rules)
      if (Object.keys(rules).length) {
        currentStep.value = 1
        return false
      }
    }
    if (!productItems.value.length) {
      Message.error('请最少增加一个关联报价产品产品')
      currentStep.value = 2
      return false
    }
    return true
  }
  function isNull(val: any) {
    return val === undefined || val === null || val === ''
  }
  // 保存信息
  async function submitData(state: number) {
    let valid = await validInfo()
    if (!valid) return false
    let params = JSON.parse(JSON.stringify(formInfo.value))
    let supplier = {
      supplierCode: formInfo.value.supplier?.supplierCode,
      supplierName: formInfo.value.supplier?.supplierName,
      supplierId: formInfo.value.supplier?.id,
    }
    let user = {
      purchaseUid: formInfo.value.user?.id,
      purchaseUname: formInfo.value.user?.userName,
    }
    params = {
      ...params,
      ...supplier,
      ...user,
      status: state,
      quoteProducts: productItems.value,
    }
    // 非梯度报价
    if (params.quoteType === 1) {
      params.quoteItems = [params.priceInfo]
    }
    delete params.user
    delete params.supplier
    delete params.priceInfo
    submitLoading.value = true
    let res: any
    if (!props.currentItem.id) {
      res = await createPurchaseQuote(params)
    } else {
      params.id = formInfo.value.id
      res = await updatePurchaseQuote(params)
    }
    submitLoading.value = false
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .add-con {
    height: calc(84vh - 240px);
  }
</style>
